package chances.epg.ui.taglib.json;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;

@SuppressWarnings("serial")
public class ToJsonTag extends TagSupport {
	private Object value;
	private String var;

	@Override
	public int doEndTag() throws JspException {
		ObjectMapper mapper = new ObjectMapper();
		mapper.setSerializationInclusion(Include.NON_EMPTY );
		try {
			String json = mapper.writeValueAsString(value);
			if (StringUtils.isEmpty(var)) {
				pageContext.getOut().write(json);
			} else {
				pageContext.setAttribute(this.var, json);
			}

		} catch (IOException e) {
			throw new JspException(e);
		} finally {
			this.value = null;
			this.var = null;
		}
		return super.doEndTag();
	}

	public Object getValue() {
		return value;
	}

	public String getVar() {
		return var;
	}

	public void setValue(Object value) {
		this.value = value;
	}

	public void setVar(String var) {
		this.var = var;
	}

}
